<?php

namespace App\Http\Controllers;

use App\AdminPermission;
use App\AdminRole;
use Illuminate\Http\Request;

class AdminRoleController extends Controller
{
    //
    public function rlist()
    {
        $adminRoles = AdminRole::all();
        return view("admin.role.list",compact("adminRoles"));

    }
    public function add()
    {
        $adminPermissions = AdminPermission::all();
        return view("admin.role.add",compact("adminPermissions"));
    }
    public function store(Request $request)
    {   
        $data = request(["name","desc"]);
        $adminRole = AdminRole::create($data);
        foreach($request->permission_id as $permission_id){
            $permission = AdminPermission::find($permission_id);
            $adminRole->assignPermission($permission);
        }
        return [
            "error"=>0,
            "info"=>"添加角色完成"
        ];
    }
    public function permission(AdminRole $adminRole)
    {
        $adminPermissions = AdminPermission::all();
        $myPermissions = $adminRole->permission;
        return view("admin.role.edit",compact("adminRole","adminPermissions","myPermissions"));
    }

    public function permissionStore(Request $request, AdminRole $adminRole)
    {
        $adminRole->name = $request->name;
        $adminRole->desc = $request->desc;
        $adminRole->save();
        $myPermissions = $adminRole->permission;
        $newPermissions = AdminPermission::find($request->permission_id);
        $addPermissions = $newPermissions->diff($myPermissions);
        $delPermissions = $myPermissions ->diff($newPermissions);
        foreach($addPermissions as $addPermission){
            $adminRole->assignPermission($addPermission);
        }
        foreach ($delPermissions as $delPermission){
            $adminRole->delPermission($delPermission);
        }
    }
}
